import asyncio
import aiohttp
import time
import json
import logging

# 获取 logger
logger = logging.getLogger(__name__)

feishu_config = {
    "tenant_access_token_url": "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
    "table_batch_create_url": "https://open.feishu.cn/open-apis/bitable/v1/apps/:app_token/tables/:table_id/records/batch_create",
    "app_id": "cli_a5fd0a9bfabb100b",
    "app_secret": "SfpMIQeMe78vf4DgjXjTugUD5VBZ2M62",
    "app_token": "DiAMbijuBaztoasHx2BctXatnUQ",
    "table_id": "tblYvSkFaujJA1WG",
}

async def fetch_base(url, params=None, headers=None, data=None, json=None, method=None, timeout=None):
    async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session:
        async with session.request(method, url, params=params, data=data, json=json) as response:
            return await response.text()

async def tenant_access_token_fetch():
    url = feishu_config["tenant_access_token_url"]
    params = {
        "app_id": feishu_config["app_id"],
        "app_secret": feishu_config["app_secret"]
    }
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "grant_type": "client_credentials"
    }
    response = await fetch_base(url, params=params, headers=headers, data=json.dumps(data), method="POST")
    return json.loads(response)["tenant_access_token"]

async def table_batch_create_demo():
    url = feishu_config["table_batch_create_url"].replace(":app_token", feishu_config["app_token"]).replace(":table_id", feishu_config["table_id"])
    headers = {
        "Authorization": f"Bearer {await tenant_access_token_fetch()}"
    }
    data = {
        "records": [
            {
                "fields": {
                    "refrence_no": "text1",
                }
            },
            {
                "fields": {
                    "refrence_no": "text1",
                }
            }
        ]
    }
    response_str = await fetch_base(url, headers=headers, json=data, method="POST")
    response = json.loads(response_str)
    if(response.get("code") != 0):
        logger.error(f"table_batch_create error: {response.get('msg')}")
    return response.get("data")

async def eccang_product_trouble_to_feishu(data_list):
    url = feishu_config["table_batch_create_url"].replace(":app_token", feishu_config["app_token"]).replace(":table_id", feishu_config["table_id"])
    headers = {
        "Authorization": f"Bearer {await tenant_access_token_fetch()}"
    }
    payload = {
        "records": []
    }

    for item in data_list:
        payload["records"].append({
            "fields": item
            })

    response_str = await fetch_base(url, headers=headers, json=payload, method="POST")
    response = json.loads(response_str)
    if(response.get("code") != 0):
        logger.error(f"table_batch_create error: {response.get('msg')}")
        logger.error(f"table_batch_create error::{response}")
    return response.get("data")

if __name__ == '__main__':
    print('feishu api start')

    # tenant_access_token = asyncio.run(tenant_access_token_fetch())
    # print(f"tenant_access_token:{tenant_access_token}", tenant_access_token)

    response = asyncio.run(table_batch_create_demo())
    print(f"response:{response}", response)

    print('feishu api end')